package com.gxa.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.gxa.common.JwtResult;
import com.gxa.common.ResponseData;
import com.gxa.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 *
 * @author bq
 * Date: 2020/10/21 15:24
 * Description:
 * Version: V1.0
 */
public class JwtHandInterceptor implements HandlerInterceptor {
    @Autowired
    private ResponseData responseData;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String token = request.getHeader("token");
        JwtResult jwtResult = JwtUtils.validateJwt(token);
        if (jwtResult.isSuccess()){//验证通过
            String newToken = JwtUtils.createJwt(jwtResult.getClaims().getId(), jwtResult.getClaims().getIssuer(), jwtResult.getClaims().getSubject(), JwtUtils.TTMILLIS);
            responseData.setToken(newToken);
            return true;
        }else {//验证失败
            if(jwtResult.getErrCode()==JwtUtils.JWT_ERRCODE_EXPIRE){
                responseData.setCode(403);
                responseData.setMsg("授权已过期");
                responseData.setData(null);
                responseData.setToken(null);
            }else if(jwtResult.getErrCode()==JwtUtils.JWT_ERRCODE_FAIL){
                responseData.setCode(400);
                responseData.setMsg("未登录请先登录");
                responseData.setData(null);
                responseData.setToken(null);
            }
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(responseData));
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
